package uk.ac.cam.echo.server;

import java.net.Socket;
import java.util.Date;

import uk.ac.cam.echo.SafeMessageQueue;
import uk.ac.cam.echo.messages.Message;

/**
 * @author Tom Smith
 */
public class ClientHandler {

	private final Socket m_Socket;
	private final ClientMessageReader m_Reader;
	private final ClientMessageWriter m_Writer;
	private final SafeMessageQueue<Message> m_Messages = new SafeMessageQueue<Message>();

	/**
	 * Initialize a handler for each client.
	 * @param sock The socket which the client is connected to.
	 */
	public ClientHandler(Socket sock) {
		this.m_Socket = sock;
				
		System.out.println(MayBallServer.DateFormat.format(new Date()) + " Client: " + this.m_Socket.getInetAddress().getHostAddress() +
				" connected on port " + this.m_Socket.getPort() + ".");
		
		// Listen for any Messages from client, act accordingly.
		this.m_Reader = new ClientMessageReader(this, this.m_Socket, this.m_Messages);
		new Thread(this.m_Reader).start();
		
		// Write any messages to the client.
		this.m_Writer = new ClientMessageWriter(this.m_Socket, this.m_Messages);
		new Thread(this.m_Writer).start();
	}
			
	/**
	 * Put a message on the queue for sending to the client.
	 * @param m The message to be sent.
	 */
	public void sendMessage(Message m) {
		this.m_Messages.put(m);
	}

}
